package com.epam.tcs.filters;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements javax.servlet.Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest hreq = (HttpServletRequest) req;
		HttpServletResponse hres = (HttpServletResponse) res;
		HttpSession session = hreq.getSession();
		String target = hreq.getRequestURI().substring(
				hreq.getContextPath().length());

		if (session.getAttribute("user") != null) {
			if ("/exit".equals(target)) {
				session.invalidate();
				hres.sendRedirect(hreq.getContextPath());
			} else {
				chain.doFilter(req, res);
			}			
		} else if (hreq.getParameter("user") != null
				&& hreq.getParameter("pass") != null) {

			if (hreq.getParameter("user").equals("Bob")
					&& hreq.getParameter("pass").equals("123")) {
				User user = new User();
				user.setName("Bob");
				user.setPassword("123");
				user.setRole("student");
				session.setAttribute("user", user);
				chain.doFilter(req, res);
			} else if (hreq.getParameter("user").equals("Serge")
					&& hreq.getParameter("pass").equals("123")) {
				User user = new User();
				user.setName("Serge");
				user.setPassword("123");
				user.setRole("teacher");
				session.setAttribute("user", user);
				chain.doFilter(req, res);
			} else {
				hreq.setAttribute("message", "Неверное имя или пароль");
				RequestDispatcher dispatcher = hreq
						.getRequestDispatcher("/login.jsp");
				dispatcher.forward(hreq, hres);
			}

		} else {
			RequestDispatcher dispatcher = hreq
					.getRequestDispatcher("/login.jsp");
			dispatcher.forward(hreq, hres);
		}

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
